package com.dudu.utils;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

/**
 * 此工具类的目的是为http请求做代理封装，适用于交易调取交易
 * 嘟嘟平台架构的参数入口为httpservletrequest，通过调用getParameter方法获取参数
 * 但是交易调取交易是无法为request设置parameter
 * 此类对这种情况进行了二次封装，将参数通过方法setAttribute方法设置
 * @author zx  
 *
 */
public class HttpRequestInvocationHandler implements InvocationHandler { 
    
	/**
	 * tomcat封装的请求
	 */
	private HttpServletRequest request;

	private static final String GETPARAMETER_METHOD = "getParameter";

	private static final String GETATTRIBUTE_METHOD = "getAttribute";

	public HttpRequestInvocationHandler(HttpServletRequest request) {
		this.request = request;
	}

	@Override
	public Object invoke(Object object, Method method, Object[] args) throws Throwable {
		if (GETPARAMETER_METHOD.equals(method.getName())) {
			Object value = method.invoke(request, args);
			if (value == null) {
				value = request.getClass().getMethod(GETATTRIBUTE_METHOD, String.class).invoke(request, args);
			}
			return value;
		} else {
			return method.invoke(request, args);
		}
	}

}
